package web.directories.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import domain.entities.*;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import services.*;
import web.CommonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Guillermo
 * Date: 09/08/12
 * Time: 14:54
 * To change this template use File | Settings | File Templates.
 */

@Namespace("/Directories/CentralVendor")
public class CentralVendorController extends ActionSupport implements ModelDriven, ServletResponseAware, ServletRequestAware {

    private CentralVendorCRUDService centralVendorService;
    private Vendorcentral vendorcentral = new Vendorcentral();
    private Protocolo protocolo = new Protocolo();
    private List<Vendorcentral> list;
    private AddressService addressService;
    private ProtocolCRUDService protocoloService;
    private ProtocoloCompromisopaisService protocoloCompromisopaisService;
    private ExternalValidationService externalValService;
    private List<Protocolo> protocols = new ArrayList<Protocolo>();
    private List<Countries> countries = new ArrayList<Countries>();
    private List<Regions> regions = new ArrayList<Regions>();
    private List<Cities> cities = new ArrayList<Cities>();
    private Countries countrySelected;
    private Regions regionSelected;
    private Cities citySelected;
    private String editableVendorId;
    private String phone;
    private List<String> categories = new ArrayList<String>();
    private RoleCRUDService roleCRUDService;
    private NormalValuesService normalValuesService;

    private List<Compromisopais> compromisopaises = new ArrayList<Compromisopais>();
    private String compromisopaisesId;

    private List<VendorType> vendorTypes;
    private VendorTypeService vendorTypeService;

    private List<NormalValuesType> normalValuesTypes;
    private NormalValuesTypeService normalValuesTypesService;

    private String protocoloid;
    private String compromisopasid;

    private List<File> files = new ArrayList<File>();
    private List<String> filesContentType = new ArrayList<String>();
    private List<String> filesFileName = new ArrayList<String>();
    private String tienenFile;

    private String indexFile;

    private HttpServletRequest request;
    private HttpServletResponse response;

    @Autowired
    public CentralVendorController(CentralVendorCRUDService centralVendorCRUDService, AddressService addressService, ProtocolCRUDService protocoloService, ProtocoloCompromisopaisService protocoloCompromisopaisService, VendorTypeService vendorTypeService, RoleCRUDService roleCRUDService, NormalValuesTypeService normalValuesTypesService, NormalValuesService normalValuesService,ExternalValidationService externalValService) {
        this.centralVendorService =  centralVendorCRUDService;
        this.addressService = addressService;
        this.protocoloCompromisopaisService = protocoloCompromisopaisService;
        this.vendorTypeService = vendorTypeService;
        this.roleCRUDService = roleCRUDService;
        this.normalValuesTypesService = normalValuesTypesService;
        this.normalValuesService = normalValuesService;
        this.externalValService = externalValService;
        vendorcentral.setAddress(new Address());
//        vendorcentral.setProtocolo(new ProtocoloCompromisopais());
        vendorcentral.setContactPerson(new ContactPerson());
        countries = addressService.getCountries();
        categories.add(Vendorcentral.CENTRAL_CATEGORY);
        categories.add(Vendorcentral.LOCAL_CATEGORY);
        normalValuesTypes = normalValuesTypesService.findAll();
        list = new ArrayList<Vendorcentral>(0);
        vendorTypes =  vendorTypeService.findAll();
    //protocols = protocoloService.getProtocols();
    }


    public Object getModel() {
        return vendorcentral;
    }

    @Action(value="main", results={
            @Result(name="success", location="/directories.central_vendor.tiles", type="tiles")
    })
    public String execute() {
        return SUCCESS;
    }

    @Action(value="list", results={
            @Result(name="success", location="/directories.central_vendor.tiles", type="tiles")
    })
    public String list() {

        CriteriaCentralVendor crV = new CriteriaCentralVendor(vendorcentral);
        list = centralVendorService.list(crV);
        vendorTypes =  vendorTypeService.findAll();
        return SUCCESS;
    }

    @Action(value="create", results={
            @Result(name="success",location="/directories.central_vendor.create.tiles", type="tiles")
    })
    public String createLaboratory() {

        if(editableVendorId != null){
            vendorcentral = centralVendorService.findById(Integer.parseInt(editableVendorId));
            countrySelected = addressService.getCountryByName(vendorcentral.getAddress().getCountry());

            regions = addressService.getRegions(countrySelected.getCountryId());
            regionSelected = addressService.getRegionByName(vendorcentral.getAddress().getProvince(), countrySelected.getCountryId().toString());

            cities = addressService.getCities(regionSelected.getRegionId());

            citySelected = addressService.getCityByName(vendorcentral.getAddress().getCity(), regionSelected.getRegionId().toString(), countrySelected.getCountryId().toString());

            phone = vendorcentral.getAddress().getPhone();
//            compromisopaises = protocoloCompromisopaisService.findCompromisoPaisByProtocoloId(vendorcentral.getProtocol().getProtocol().getId());

  //          compromisopasid = vendorcentral.getProtocol().getCompromisopais().getId().toString();

        }

        vendorTypes =  vendorTypeService.findAll();
        VendorType v = new VendorType( -2, "Other");
        vendorTypes.add(v);

        return SUCCESS;
    }

    @Action(value="save", results={
            @Result(name="success",location="main", type="redirectAction")
    })
    public String saveVendor() throws IOException {
        addressService.checkCity(   vendorcentral.getAddress().getCity(),
                vendorcentral.getAddress().getProvince(),
                vendorcentral.getAddress().getCountry());

        vendorTypeService.checkType(vendorcentral.getType().getDescripcion());

//        vendorcentral.setProtocol(protocoloCompromisopaisService.getByProtocoloIdCompromisopaisId(protocoloid,Integer.parseInt(compromisopasid)));
        if( !vendorcentral.getType().getId().equals(-2) )
            vendorcentral.setType(vendorTypeService.findbyId(vendorcentral.getType().getId()));
        else
             vendorcentral.setType(vendorTypeService.findByDescripcion(vendorcentral.getType().getDescripcion()));
//        vendorcentral.setProtocolo(null);


        Iterator<ExternalValidation> itVal = vendorcentral.getExternalValidations().iterator();
        List<Integer> aBorrar = new ArrayList<Integer>();
        Integer index = 0;
        while(itVal.hasNext()){
            ExternalValidation actual = itVal.next();
            if(actual != null && actual.getExpirationDate() != null && actual.getType() != null && !actual.getType().equals("") ){
                actual.setVendorcentral(vendorcentral);
            }
            else{
                aBorrar.add(index);
            }
            index++;
        }

        int borrados = 0;
        Iterator<Integer> itBorrar = aBorrar.iterator();
        while(itBorrar.hasNext()){
            int indice = itBorrar.next() - borrados;
            Integer id = vendorcentral.getExternalValidations().get(indice).getId();
            if( id != null ){
                ExternalValidation extABorrar = externalValService.findById(id);
                externalValService.delete(extABorrar);
            }
            vendorcentral.getExternalValidations().remove(indice);
            borrados++;
        }

        aBorrar.clear();

        if(vendorcentral.getType().getDescripcion().equals("Laboratory")){
            String [] idsConFile = null;
            int fileIndex = -1;
            if(!tienenFile.equals("")){
                idsConFile = tienenFile.split(", ");
                fileIndex = 0;
            }

            Iterator<NormalValues> itNv = vendorcentral.getNormalValues().iterator();
            index = 0;
            while(itNv.hasNext()){
                NormalValues actual = itNv.next();
                if(actual != null && actual.getExpirationDate() != null){
               /*     if(actual.getId() != null){
                        actual = normalValuesService.findById(actual.getId());
                        actual.setVendorcentral(vendorcentral);
                    }
                    else{*/
                        actual.setVendorcentral(vendorcentral);
                        if(actual.getFileName() == null || actual.getFileName().equals(""))
                            if(idsConFile != null && fileIndex < idsConFile.length && idsConFile[fileIndex].equals(index.toString())){
                                actual.setFileName(filesFileName.get(fileIndex));
                                FileInputStream fis;
                                byte[] content = null;
                                fis = new FileInputStream(files.get(fileIndex));
                                content = new byte[fis.available()];
                                fis.read(content);
                                fis.close();
                                actual.setFile(content);
                                fileIndex++;
                            }
                        NormalValuesType type = normalValuesTypesService.findbyId(actual.getType().getId());
                        actual.setType(type);
                        type.addNormalValues(actual);
                   // }
                }
                else{
                    aBorrar.add(index);
                }
                index++;
            }

            borrados = 0;
            itBorrar = aBorrar.iterator();
            while(itBorrar.hasNext()){
                int indice = itBorrar.next() - borrados;
                Integer id = vendorcentral.getNormalValues().get(indice).getId();
                if(id != null){
                    NormalValues extABorrar = normalValuesService.findById(id);
                    normalValuesService.delete(extABorrar);
                }
                vendorcentral.getNormalValues().remove(indice);
                borrados++;
            }
        }
        else{
            vendorcentral.getNormalValues().clear();
        }

        centralVendorService.save(vendorcentral);

        return SUCCESS;
    }

    @Action(value="downloadFile", results={
            @Result(name="success",location="/directories.central_vendor.create.tiles", type="tiles")
    })
    public String downloadFile() throws IOException {
        if( vendorcentral.getId() != null && vendorcentral.getId() != 0){
            Vendorcentral vc =   centralVendorService.findById(vendorcentral.getId());
            NormalValues nv = vc.getNormalValues().get(Integer.parseInt(indexFile));
            if( nv != null){
                String[] ext = nv.getFileName().split("\\.");
                // Initialize response.
                response.reset();
                if( ext[1].equals("pdf"))
                    response.setContentType("application/pdf");
                else
                    response.setContentType("application/doc");
                response.setHeader("Content-disposition", "attachment; filename=\""+nv.getFileName()+"\"");
                // Write file to response.
                OutputStream output = response.getOutputStream();
                output.write(nv.getFile());
                output.close();
            }
        }
        return SUCCESS;
    }

    @Action(value="delete", results={
            @Result(name="success",location="main", type="redirectAction")
    })
    public String deleteLaboratory() {
        vendorcentral = centralVendorService.findById(vendorcentral.getId());

        centralVendorService.delete(vendorcentral);

        return SUCCESS;
    }

    @Action(value="getVendorByName", results={
            @Result(name="success",location="/WEB-INF/jsp/Protocols/globalVendorSelection/vendorsWindow.jsp")
    })
    public String getVendorByName() {
        list = centralVendorService.listByNameAndCategoryAndType(
                vendorcentral.getName(),
                Vendorcentral.CENTRAL_CATEGORY,
                vendorcentral.getType().getId());

        return SUCCESS;
    }

    @Action(value="getLocalVendorByName", results={
            @Result(name="success",location="/WEB-INF/jsp/Protocols/globalVendorSelection/vendorsWindow.jsp")
    })
    public String getLocalVendorByName() {
        list = centralVendorService.listByNameAndCategoryAndType(
                vendorcentral.getName(),
                Vendorcentral.LOCAL_CATEGORY,
                vendorcentral.getType().getId());

        return SUCCESS;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public List<Vendorcentral> getList() {
        return list;
    }

    public void setList(List<Vendorcentral> list) {
        this.list = list;
    }

    public List<Countries> getCountries() {
        return countries;
    }

    public void setCountries(List<Countries> countries) {
        this.countries = countries;
    }

    public String getEditableVendorId() {
        return editableVendorId;
    }

    public void setEditableVendorId(String editableVendorId) {
        this.editableVendorId = editableVendorId;
    }

    public List<Cities> getCities() {
        return cities;
    }

    public void setCities(List<Cities> cities) {
        this.cities = cities;
    }

    public List<Regions> getRegions() {
        return regions;
    }

    public void setRegions(List<Regions> regions) {
        this.regions = regions;
    }

    public Countries getCountrySelected() {
        return countrySelected;
    }

    public void setCountrySelected(Countries countrySelected) {
        this.countrySelected = countrySelected;
    }

    public Cities getCitySelected() {
        return citySelected;
    }

    public void setCitySelected(Cities citySelected) {
        this.citySelected = citySelected;
    }

    public Regions getRegionSelected() {
        return regionSelected;
    }

    public void setRegionSelected(Regions regionSelected) {
        this.regionSelected = regionSelected;
    }

    public Protocolo getProtocolo() {
        return protocolo;
    }

    public void setProtocolo(Protocolo protocolo) {
        this.protocolo = protocolo;
    }

    public List<Protocolo> getProtocols() {
        return protocols;
    }

    public void setProtocols(List<Protocolo> protocols) {
        this.protocols = protocols;
    }

    public Vendorcentral getVendorcentral() {
        return vendorcentral;
    }

    public void setVendorcentral(Vendorcentral vendorcentral) {
        this.vendorcentral = vendorcentral;
    }

    public String getProtocoloid() {
        return protocoloid;
    }

    public void setProtocoloid(String protocoloid) {
        this.protocoloid = protocoloid;
    }

    public List<Compromisopais> getCompromisopaises() {
        return compromisopaises;
    }

    public void setCompromisopaises(List<Compromisopais> compromisopaises) {
        this.compromisopaises = compromisopaises;
    }

    public List<VendorType> getVendorTypes() {
        return vendorTypes;
    }

    public void setVendorTypes(List<VendorType> vendorTypes) {
        this.vendorTypes = vendorTypes;
    }

    public String getCompromisopasid() {
        return compromisopasid;
    }

    public void setCompromisopasid(String compromisopasid) {
        this.compromisopasid = compromisopasid;
    }

    public List<String> getCategories() {
        return categories;
    }

    public void setCategories(List<String> categories) {
        this.categories = categories;
    }

    public List<NormalValuesType> getNormalValuesTypes() {
        return normalValuesTypes;
    }

    public void setNormalValuesTypes(List<NormalValuesType> normalValuesTypes) {
        this.normalValuesTypes = normalValuesTypes;
    }

    public List<String> getFilesFileName() {
        return filesFileName;
    }

    public void setFilesFileName(List<String> filesFileName) {
        this.filesFileName = filesFileName;
    }

    public List<File> getFiles() {
        return files;
    }

    public void setFiles(List<File> files) {
        this.files = files;
    }

    public List<String> getFilesContentType() {
        return filesContentType;
    }

    public void setFilesContentType(List<String> filesContentType) {
        this.filesContentType = filesContentType;
    }

    public String getTienenFile() {
        return tienenFile;
    }

    public void setTienenFile(String tienenFile) {
        this.tienenFile = tienenFile;
    }

    public String getIndexFile() {
        return indexFile;
    }

    public void setIndexFile(String indexFile) {
        this.indexFile = indexFile;
    }

    @Override
    public void setServletRequest(javax.servlet.http.HttpServletRequest request) {
        this.request   = request;
    }

    @Override
    public void setServletResponse(javax.servlet.http.HttpServletResponse response) {
        this.response = response;
    }
}
